package com.heer.gymnasium.activity;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.heer.api.ResponseData.ApiResponse;
import com.heer.api.callback.BaseCallback;
import com.heer.api.constants.IConstants;
import com.heer.api.sign.SDKRuntimeException;
import com.heer.api.sign.SignHelper;
import com.heer.gymnasium.R;
import com.heer.gymnasium.adapter.UserHobbyAdapter;
import com.heer.gymnasium.constant.Extras;
import com.heer.gymnasium.event.BaseEvent;
import com.heer.gymnasium.permission.EasyPermissions;
import com.heer.gymnasium.util.LoadImageUtil;
import com.heer.gymnasium.util.Session;
import com.heer.gymnasium.widget.GlideCircleImage;
import com.heer.imagepick.PhotoWallSingleActivity;
import com.heer.model.UserAvatarBean;
import com.heer.model.UserHobbyBean;
import com.heer.model.UserInfoBean;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

import static com.heer.gymnasium.event.EventConstant.USER_CENTER_REFRESH;

/**
 * Created by heer on 17/4/10.
 */

public class UserCenterActivity extends BaseActivity {
    @BindView(R.id.edit_nick)
    EditText editNick;
    @BindView(R.id.radio_male)
    RadioButton radioMale;
    @BindView(R.id.radio_female)
    RadioButton radioFemale;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.edit_cm)
    EditText editCm;
    @BindView(R.id.edit_kg)
    EditText editKg;
    @BindView(R.id.gv_hobby)
    GridView gvHobby;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    @BindView(R.id.ivAvatar)
    ImageView ivAvatar;

    private UserInfoBean mData;
    private UserHobbyAdapter mAdapter;
    private String hobby;

    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.activity_user_center);
        mData = (UserInfoBean) getIntent().getSerializableExtra(Extras.EXTRA_DATA);
    }

    @Override
    protected void initView() {
        super.initView();
        try {
            editNick.setText(URLDecoder.decode(mData.getUserInfo().getNickname(), "utf-8"));
            Glide.with(mContext)
                    .load(LoadImageUtil.getLoadImageUrl(URLDecoder.decode(mData.getUserInfo().getAvatar(), "utf-8")))
                    .transform(new GlideCircleImage(mContext))
                    .placeholder(R.mipmap.ic_default_avatar)
                    .into(ivAvatar);
            hobby = mData.getUserInfo().getH_id() == null ? "" : URLDecoder.decode(mData.getUserInfo().getH_id(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        radioGroup.check(mData.getUserInfo().getSex().equals("1") ? R.id.radio_male : R.id.radio_female);
        editCm.setText(mData.getUserInfo().getHeight());
        editKg.setText(mData.getUserInfo().getWeight());
        gvHobby.setAdapter(mAdapter = new UserHobbyAdapter(mContext));
        gvHobby.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mAdapter.getItem(position).setSelected(!mAdapter.getItem(position).isSelected());
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void loadData() {
        super.loadData();
        mAppHelper.apiService().getUserHobby(Session.getUserId()).enqueue(new BaseCallback<ApiResponse<List<UserHobbyBean>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<UserHobbyBean>>> call, Response<ApiResponse<List<UserHobbyBean>>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful() && response.body().isSccessful()) {
                    List<UserHobbyBean> list = response.body().getData();
                    String[] hids = hobby.split(",");
                    for (UserHobbyBean bean : list) {
                        bean.setSelected(false);
                        for (String hid : hids) {
                            if (hid.equals(bean.getId())) {
                                bean.setSelected(true);
                            }
                        }
                    }
                    mAdapter.setItems(response.body().getData());
                }
                if (response.body().isTokenExpire()) {
                    toLogin();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<UserHobbyBean>>> call, Throwable t) {
                super.onFailure(call, t);
            }
        });
    }

    @OnClick({R.id.btn_submit, R.id.ivAvatar})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
                String nickname = null;
                String sex;
                String height = null;
                String weight = null;
                String hobby = "";

                if (!TextUtils.isEmpty(editNick.getText().toString().trim()))
                    nickname = editNick.getText().toString().trim();
                if (radioGroup.getCheckedRadioButtonId() == R.id.radio_female)
                    sex = "0";
                else
                    sex = "1";
                if (!TextUtils.isEmpty(editKg.getText().toString().trim()))
                    weight = editKg.getText().toString().trim();
                if (!TextUtils.isEmpty(editCm.getText().toString().trim()))
                    height = editCm.getText().toString().trim();

                List<UserHobbyBean> itemList = mAdapter.getItemList();
                for (int i = 0; i < itemList.size(); i++) {
                    UserHobbyBean item = itemList.get(i);
                    if (item.isSelected()) {
                        if (i > 0) hobby += ",";
                        hobby += item.getId();
                    }
                }

                try {
                    mAppHelper.apiService().updateUserInfo(URLDecoder.decode(Session.getUserPicUrl(), "utf-8"), nickname, sex, height, weight, TextUtils.isEmpty(hobby) ? null : hobby).enqueue(new BaseCallback<ApiResponse>() {
                        @Override
                        public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                            super.onResponse(call, response);
                            if (response.isSuccessful() && response.body().isSccessful()) {
                                Toast.makeText(mContext, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                                EventBus.getDefault().post(new BaseEvent(USER_CENTER_REFRESH, String.valueOf(0)));
                                finish();
                            }
                        }

                        @Override
                        public void onFailure(Call<ApiResponse> call, Throwable t) {
                            super.onFailure(call, t);
                        }
                    });
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.ivAvatar:
                String[] perms = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
                if (EasyPermissions.hasPermissions(mContext, perms)) {
                    Intent intent = new Intent(mContext,
                            PhotoWallSingleActivity.class);
                    startActivityForResult(intent, 0);
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 100) {
            int code = data.getIntExtra("code", -1);
            if (code != 100) {
                return;
            }
            List<String> list = data.getStringArrayListExtra("paths");
            if (null != list && list.size() > 0) {
                final String path = list.get(0);
                Log.e("zxw", "onActivityResult: " + path);
                File file = new File(path);
                RequestBody requestFile =
                        RequestBody.create(MediaType.parse("multipart/form-data"), file);

                MultipartBody.Part body = MultipartBody.Part.createFormData("pic", file.getName(), requestFile);

                SignHelper sign = new SignHelper("");

                try {
                    mAppHelper.apiService().avatarUpdate(RequestBody.create(MediaType.parse("text/plain"), IConstants.AVATAR_UPDATE)
                            , RequestBody.create(MediaType.parse("text/plain"), sign.GetParameter("key"))
                            , RequestBody.create(MediaType.parse("text/plain"), sign.GetParameter("unixtime"))
                            , RequestBody.create(MediaType.parse("text/plain"), sign.GetParameter("token"))
                            , RequestBody.create(MediaType.parse("text/plain"), sign.getSign())
                            , RequestBody.create(MediaType.parse("text/plain"), "jpg"), body).enqueue(new BaseCallback<ApiResponse<UserAvatarBean>>() {
                        @Override
                        public void onResponse(Call<ApiResponse<UserAvatarBean>> call, Response<ApiResponse<UserAvatarBean>> response) {
                            super.onResponse(call, response);
                            if (response.isSuccessful() && response.body().isSccessful()) {
                                Glide.with(mContext)
                                        .load(LoadImageUtil.getLoadImageUrl(response.body().getData().getAvatar()))
                                        .transform(new GlideCircleImage(mContext))
                                        .placeholder(R.mipmap.ic_default_avatar)
                                        .into(ivAvatar);
                                Session.setUserPicUrl(response.body().getData().getAvatar());
                            }
                        }

                        @Override
                        public void onFailure(Call<ApiResponse<UserAvatarBean>> call, Throwable t) {
                            super.onFailure(call, t);
                        }
                    });
                } catch (SDKRuntimeException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
